
library(tidyverse)
library(sf)
library(lubridate)

wd <- 'C:\\Users\\msant\\Dropbox\\Sugarcane Offline Data\\ProtectedAreas'
setwd(wd)

grid <- st_read(dsn = '..\\GridBuild\\CanasatData.gdb', layer = 'G1kmMiR')
CanasatProjStr <- st_crs(grid)

indi <- st_read(dsn = 'indi2010.shp', options = "ENCODING=WINDOWS-1252")
st_crs(indi) = 4618 # projection used for protected areas dataset (see README)
indi <- indi %>%
  st_transform(indi, crs = CanasatProjStr) %>%
  select(GRUPOS9, DATADOC16) %>%
  rename(GRUPOS = GRUPOS9, DATADOC = DATADOC16) %>%
  mutate(DATADOC = ymd(DATADOC)) %>%
  mutate(DATADOCy = as.integer(year(DATADOC))) %>%
  filter(DATADOCy < 2014) # use only indian land created before 2014

ucstodas <- st_read(dsn = 'ucstodas.shp', options = "ENCODING=WINDOWS-1252")
st_crs(ucstodas) = 4618 # projection used for protected areas dataset (see README)
ucstodas <- ucstodas %>% 
  st_transform(crs = CanasatProjStr) %>%
  filter(CATEGORI3 != "�rea de Prote��o Ambiental") %>% # Eliminate APA from protected (most of them in the relavant region 
                                                        # do have sugarcane fields)
  select(CATEGORI3, ANO_CRIA6) %>%
  rename(CATEGORIA = CATEGORI3, ANO_CRIACAO = ANO_CRIA6) %>%
  mutate(ANO_CRIACAO = as.character(ANO_CRIACAO)) %>% # change to string to correct some gibberish
  mutate(ANO_CRIACAO = str_replace(ANO_CRIACAO, "Gerais de 22/09/1998", "1998")) %>% # correcting gibberish
  mutate(ANO_CRIACAO = str_replace(ANO_CRIACAO, "setembro de 2013 de 15/10/2013", "2013")) %>% # correcting gibberish
  mutate(ANO_CRIACAO = str_replace(ANO_CRIACAO, "e 2016 de 11/05/2016", "2016")) %>% # correcting gibberish
  mutate(ANO_CRIACAO = as.integer(ANO_CRIACAO)) %>%
  filter(ANO_CRIACAO < 2014) # use only UCS created before 2014

# Join Indian land to Grid
grid <- grid %>%
  st_join(indi, join = st_intersects, left = TRUE) %>%
  mutate(indian = as.integer(!is.na(GRUPOS))) %>%
  select(TARGET_FID, indian)

# Join UCS to Grid
grid <- grid %>%
  st_join(ucstodas, join = st_intersects, left = TRUE) %>%
  mutate(ucs = as.integer(!is.na(CATEGORIA))) %>%
  select(-CATEGORIA, -ANO_CRIACAO)

grid <- distinct(grid, TARGET_FID, indian, ucs, .keep_all = TRUE)
st_write(grid, 'G1kmMiRProtected.shp', delete_dsn = TRUE)
grid$Shape <- NULL
grid <- as_tibble(grid)
write_csv(grid, '..\\GridBuild\\Tables\\G1kmMiRProtected.csv')




